﻿using OAZCSharpSdk.OAZ.Plugin.Extensions;
using OAZCSharpSdk.TyphoonInfo.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace OAZCSharpSdk.TyphoonInfo
{
    public class TyphoonInfoPlugin : OAZ.Plugin.OAZPlugin
    {
        public TyphoonInfoPlugin() : base("台风信息", "1.0.0", "初夏", "台风信息查询，初夏插件交流群：281089761")
        {
            Enable += TyphoonInfoPlugin_Enable;
            GroupMessage += TyphoonInfo_GroupMessage;
        }

        private void TyphoonInfoPlugin_Enable(object sender, OAZ.Plugin.Events.PluginEnableArgs e)
        {
            //Debug();
        }

        private void TyphoonInfo_GroupMessage(object sender, OAZ.Plugin.Events.PluginGroupMessageEventArgs e)
        {
            if (e.Mentions.Any() && !e.Mentions.Any(x => x == e.RobotQQ))
            {
                return;
            }
            if (e.Command == "/当前台风")
            {
                string json = Request("http://typhoon.zjwater.gov.cn/Api/TyhoonActivity");
                var typlist = json.JsonDeserialize<List<TyphoonInfo.Model.TyphoonActivity>>();
                if (!typlist.Any())
                {
                    e.SendMessage("当前无台风", true);
                }
                else
                {
                    e.SendMessage("====当前台风====" + Environment.NewLine + string.Join(Environment.NewLine, typlist.Select(x => $"[{x.name}({x.enname})]{Environment.NewLine}风力:{x.power}级({x.strong})")) + Environment.NewLine + "====当前台风====", true);
                }
            }
            else if (e.Command == "/台风列表")
            {
                if (!e.Args.Any())
                {
                    e.SendMessage($"请输入你需要查询的年份，例如：{e.Command} {DateTime.Now.Year - 1}", true);
                }
                else if (!int.TryParse(e.Args[0], out var year) || year > DateTime.Now.Year)
                {
                    e.SendMessage($"请输入你正确的年份，例如：{e.Command} {DateTime.Now.Year - 1}", true);
                }
                else
                {
                    string json = Request($"http://typhoon.zjwater.gov.cn/Api/TyphoonList/{year}");
                    var typlist = json.JsonDeserialize<List<TyphoonInfo.Model.TyphoonList>>();
                    if (!typlist.Any())
                    {
                        e.SendMessage(year + "年暂无出现台风", true);
                    }
                    e.SendMessage($"{Environment.NewLine}===={year}年台风====" + Environment.NewLine + string.Join(Environment.NewLine, typlist.Select(x => $"[{x.name}({x.enname})]{Environment.NewLine}生成时间：{x.starttime.ToString("yyyy-MM-dd HH:mm:ss")}{Environment.NewLine}消散时间：{x.endtime1}")) + Environment.NewLine + $"===={year}年台风====", true);
                }
            }
            else if (e.Command == "/台风信息")
            {
                if (!e.Args.Any())
                {
                    e.SendMessage($"请输入你需要查询的名称，例如：{e.Command} 201822山竹", true);
                }
                else
                {
                    string json = Request($"http://typhoon.zjwater.gov.cn/Api/TyphoonSearch/{e.Args[0]}");
                    var typlist = json.JsonDeserialize<List<TyphoonInfo.Model.TyphoonSearch>>();
                    if (!typlist.Any())
                    {
                        e.SendMessage($"没有找到台风{e.Args[0]}", true);
                    }
                    else if (typlist.Count() > 1)
                    {
                        e.SendMessage($"{Environment.NewLine}当前查询的名称存在多个台风，请输入准确的台风名称：{Environment.NewLine}{string.Join(Environment.NewLine, typlist.Select(x => x.name))}",true);
                    }
                    else
                    {
                        json = Request($"http://typhoon.zjwater.gov.cn/Api/TyphoonInfo/{typlist.FirstOrDefault().value}");
                        var typinfo = json.JsonDeserialize<List<TyphoonInfo.Model.TyphoonInfo>>();
                        if (typinfo.Count != 1)
                        {
                            e.SendMessage($"出现错误，请截图向插件作者反馈。当前错误消息：" + e.SafeContent, true);
                        }
                        var typ = typinfo.FirstOrDefault();
                        var point = typ.points.OrderByDescending(x => int.Parse(x.power)).FirstOrDefault();
                        e.CreateMessage()
                            .AppendAtQQ()
                            .AppendLine()
                            .AppendLine($"[{typ.name}({typ.enname})]")
                            .AppendLine($"生成时间：{typ.starttime.ToString("yyyy-MM-dd HH:mm:ss")}")
                            .AppendLine($"风力级别(最高)：{point.power}({point.strong})")
                            .AppendLine($"风力级别(平均)：{Math.Round((typ.points.Average(x=>int.Parse(x.power))), 0)}级")
                            .AppendLine($"登陆次数：{typ.land.Count}")
                            .AppendLine(string.Join(Environment.NewLine, typ.land.Select(x => x.info + " (具体地址：" + x.landaddress + ",级别：" + x.strong + ")")))
                            .AppendLine($"数据最后更新时间：{typ.endtime}")
                            .Done();
                    }
                }
            }
        }

        private static string Request(string uri)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.ContentType = "application/json";
            var response = (HttpWebResponse)request.GetResponseAsync().Result;
            using (var stream = response.GetResponseStream())
            {
                using (var reader = new StreamReader(stream))
                {
                    return reader.ReadToEnd();

                }
            }
        }
    }
}
